package com.pubsys.main.client.componentes.referenciascellview;

import java.util.LinkedList;

import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.gwt.view.client.SingleSelectionModel;
import com.pubsys.main.shared.model.Referencia;

public class ReferenciaCellView extends CellTable<Referencia> implements Handler  {
	private static final ProvidesKey<Referencia> KEY_PROVIDER = new ProvidesKey<Referencia>() {		
		@Override
		public Object getKey(Referencia item) {
			return item.getId();
		}
	};
	
	
	TextColumn<Referencia> texto = new TextColumn<Referencia>() {		
		@Override
		public String getValue(Referencia object) {
			//Aqui montamos o texto para mostrar na celula
			return object.getFormatoABNT();
		}
	};
	
	
	private SingleSelectionModel<Referencia> listenerSelecaoUnica = new SingleSelectionModel<Referencia>();


	private Referencia selectedObject;;
		
	public ReferenciaCellView() {
		this.configuraPraVisualizacao();
	}

	
	private void configuraPraVisualizacao() {
		this.addColumn(texto, "Referência");
		
		this.setSelectionModel(listenerSelecaoUnica);
		this.listenerSelecaoUnica.addSelectionChangeHandler(this);
		
		this.setRowData(new LinkedList<Referencia>());
	}

	
	public HandlerRegistration addReferenciaSelectedHandler(ReferenciaCellTableEventHandler handler){
		return this.addHandler(handler, ReferenciaCellTableSelectEvent.TYPE);
	}
/*
	@Override
	public void onCellPreview(CellPreviewEvent<Referencia> event) {
		this.fireEvent(new ReferenciaCellTableSelectEvent(event.getValue()));
//		Window.alert(event.getValue().getTitulo());
	}*/


	@Override
	public void onSelectionChange(SelectionChangeEvent event) {
		this.selectedObject = this.listenerSelecaoUnica.getSelectedObject();
		if (this.selectedObject != null && this.selectedObject instanceof Referencia){
			this.fireEvent(new ReferenciaCellTableSelectEvent(this.selectedObject));			
		}
	}


	public void cancelSelection() {
		if (this.selectedObject != null)
			this.listenerSelecaoUnica.setSelected(this.selectedObject, false);
	}
}
